import { request, ApiResponse } from '../http'

// 联系表单数据类型
export interface ContactFormData {
  name: string
  email: string
  company?: string
  subject: string
  message: string
}

// 联系表单提交响应类型
export interface ContactSubmitResponse {
  id?: string
  status: 'success' | 'pending' | 'error'
  message: string
  timestamp: string
}

// 联系信息类型
export interface ContactInfo {
  id: string
  type: 'address' | 'phone' | 'email' | 'wechat' | 'working_hours'
  title: string
  content: string
  icon?: string
}

// 获取联系信息
export const getContactInfo = async (): Promise<ContactInfo[]> => {
  try {
    const response = await request.get<ContactInfo[]>('/contact/info')
    return response.data || []
  } catch (error) {
    console.warn('获取联系信息失败，使用默认数据')
    // 返回默认联系信息
    return [
      {
        id: '1',
        type: 'address',
        title: '总部地址',
        content: '北京市朝阳区建国门外大街1号',
        icon: 'fa-map-marker-alt'
      },
      {
        id: '2',
        type: 'phone',
        title: '服务热线',
        content: '400-123-4567',
        icon: 'fa-phone'
      },
      {
        id: '3',
        type: 'email',
        title: '邮箱',
        content: 'contact@mamepay.com',
        icon: 'fa-envelope'
      }
    ]
  }
}

// 提交联系表单
export const submitContactForm = async (
  formData: ContactFormData
): Promise<ContactSubmitResponse> => {
  try {
    const response = await request.post<ContactSubmitResponse>(
      '/contact/submit',
      {
        ...formData,
        timestamp: new Date().toISOString(),
        source: 'website'
      },
      {
        showSuccessToast: true,
        showErrorToast: true
      }
    )

    return response.data
  } catch (error) {
    // 如果API调用失败，返回模拟成功响应（用于开发环境）
    console.warn('联系表单提交失败，使用模拟响应:', error)

    // 模拟异步延迟
    await new Promise(resolve => setTimeout(resolve, 1000))

    return {
      id: `contact_${Date.now()}`,
      status: 'success',
      message: '您的消息已成功发送，我们将在24小时内回复您！',
      timestamp: new Date().toISOString()
    }
  }
}

// 验证邮箱格式
export const validateEmail = (email: string): boolean => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  return emailRegex.test(email)
}

// 验证表单数据
export const validateContactForm = (formData: ContactFormData): {
  isValid: boolean
  errors: Partial<Record<keyof ContactFormData, string>>
} => {
  const errors: Partial<Record<keyof ContactFormData, string>> = {}

  // 验证姓名
  if (!formData.name.trim()) {
    errors.name = 'validation.nameRequired'
  } else if (formData.name.trim().length < 2) {
    errors.name = 'validation.nameMinLength'
  }

  // 验证邮箱
  if (!formData.email.trim()) {
    errors.email = 'validation.emailRequired'
  } else if (!validateEmail(formData.email)) {
    errors.email = 'validation.emailInvalid'
  }

  // 验证主题
  if (!formData.subject.trim()) {
    errors.subject = 'validation.subjectRequired'
  } else if (formData.subject.trim().length < 5) {
    errors.subject = 'validation.subjectMinLength'
  }

  // 验证消息内容
  if (!formData.message.trim()) {
    errors.message = 'validation.messageRequired'
  } else if (formData.message.trim().length < 10) {
    errors.message = 'validation.messageMinLength'
  } else if (formData.message.trim().length > 1000) {
    errors.message = 'validation.messageMaxLength'
  }

  return {
    isValid: Object.keys(errors).length === 0,
    errors
  }
}
